package club.xyes.zkh.ecommerce.web.api.controller;

import club.xyes.zkh.ecommerce.commons.entity.Shop;
import club.xyes.zkh.ecommerce.commons.exception.BadRequestException;
import club.xyes.zkh.ecommerce.service.ShopService;
import club.xyes.zkh.ecommerce.web.controller.AbstractControllerSupport;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * Create by 郭文梁 2019/5/10 0010 16:33
 * WxMpController
 * 微信小程序相关数据访问控制器
 *
 * @author 郭文梁
 * @data 2019/5/10 0010
 */
@RestController
@RequestMapping("/mp")
@Slf4j
public class WxMpController extends AbstractControllerSupport {
    /**
     * 微信小程序验证文件内容
     */
    private static final String WX_MP_VALIDATE_FILE_CONTENT = "dd7354594f63dee41e1322f35efbb580";
    private final ShopService shopService;

    @Autowired
    public WxMpController(ShopService shopService) {
        this.shopService = shopService;
    }

    /**
     * 微信小程序二维码链接验证
     *
     * @param filename 文件名
     * @return 文件内容
     */
    @GetMapping("/{filename}.txt")
    @ApiOperation("微信小程序二维码链接验证")
    public String mpValidate(@PathVariable("filename") String filename) {
        log.debug("mp validate:{}", filename);
        return WX_MP_VALIDATE_FILE_CONTENT;
    }

    /**
     * 微信小程序支付页面
     *
     * @return GR
     */
    @GetMapping("/{sn}")
    @ApiOperation("支付链接")
    public ModelAndView mpPay(@PathVariable("sn") String sn) {
        log.debug("Wx mp pay,sn={}", sn);
        ModelAndView mv = new ModelAndView();
        Shop shop = shopService.findBySn(sn);
        if (shop == null) {
            throw new BadRequestException("商铺不存在");
        }
        mv.setViewName("redirect:" + shop.getGeneralPayUrl());
        return mv;
    }
}
